package cn.chaos.nio.exercise;

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JHttpServerNio1 {


    private static final int NUM_THREADS = 50;
    private static final String INDEX_FILE = "index.html";

    private final File rootDirectory;
    private final int port;

    public JHttpServerNio1(File rootDirectory, int port) {

        if (!rootDirectory.isDirectory()) {
            throw new IllegalArgumentException("rootDirectory is not directory!");
        }
        this.rootDirectory = rootDirectory;
        this.port = port;
    }

    public void start() {

        InetSocketAddress address = new InetSocketAddress(port);


        try (ServerSocketChannel server = ServerSocketChannel.open()) {

            server.bind(address);

            while (true && server != null) {
                SocketChannel connection = server.accept();

                ByteBuffer buffer = ByteBuffer.allocate(16 * 1024);

                StringBuilder sb = new StringBuilder();

                while ((connection.read(buffer)) != -1) {

                    buffer.flip();
                    while (buffer.hasRemaining()) {
                        sb.append((char)buffer.get());
                    }
                    buffer.compact();
                    if (sb.length() > 4 && sb.substring(sb.length() -4).equals("\r\n\r\n")) {
                        break;
                    }
                }
                System.out.println(sb);

                byte[] bytes = Files.readAllBytes(Paths.get(rootDirectory.getPath() + "/index.html"));
                connection.write(ByteBuffer.wrap("HTTP/1.1 200 OK\n".getBytes()));
                connection.write(ByteBuffer.wrap("Content-Type: text/html; charset=UTF-8\n".getBytes()));
                connection.write(ByteBuffer.wrap(("Content-Length: "+ (bytes.length) + "\n").getBytes()));
                connection.write(ByteBuffer.wrap("\r\n".getBytes()));
                connection.write(ByteBuffer.wrap(bytes));
                connection.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        File rootDirectory = new File("/Users/chengchao/temp/mydocroot");
        int port = 11111;

        try {
            new JHttpServerNio1(rootDirectory, port).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
